import csv

from flask import Flask, jsonify
from flask_cors import CORS
from flask_restful import Resource, reqparse, Api, fields, marshal
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123qwe!!@192.168.0.86:3306/exchange_web?charset=utf8'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_BINDS'] = {
    'db1': 'mysql+pymysql://root:123qwe!!@192.168.0.86:3306/exchange_web?charset=utf8',
    'db2': 'mysql+pymysql://root:123qwe!!@192.168.0.86:3306/trade_history?charset=utf8'
}

db = SQLAlchemy(app)
api = Api(app)

COIN = ['USD', 'BTC', 'BCH', 'ETH', 'ETC', 'DASH', 'XRP', 'XLM', 'DOGE', 'LTC']
from model import User, JuniorIdentity, BalanceHistory

class Base_user(Resource):
    base_get_parse = reqparse.RequestParser()
    base_get_parse.add_argument('user_id', type=int, location='args')
    base_get_parse.add_argument('mobile', type=str, location='args')
    base_get_parse.add_argument('coin', type=str, location='args', default='BTC')
    base_get_parse.add_argument('limit', type=str, location='args')
    base_get_parse.add_argument('page', type=str, location='args')

    user_base = {
        'user_id': fields.Integer,
        'email': fields.String,
        'mobile': fields.String,
    }

    user_order = {
        'time': fields.Integer,
        'user_id': fields.Integer,
        'asset': fields.String,
        'business': fields.String,
        'change': fields.Float,
        'balance': fields.Float,
    }

class SelcetUser(Base_user):
    """查询用户基本信息"""
    def get(self):
        parse = self.base_get_parse.parse_args()
        if parse.mobile:
            user = User.query.filter(User.mobile == parse.mobile).first()
        if parse.user_id:
            user = User.query.filter(User.user_id == parse.user_id).first()

        junior_data = JuniorIdentity.query.filter(JuniorIdentity.user_id == user.user_id).first()

        junior_name = ""
        junior_address = ""
        junior_card = ""

        if junior_data:
            junior_name = junior_data.last_name + junior_data.middle_name + junior_data.first_name
            junior_address = junior_data.id_address
            junior_card = junior_data.id_card


        rest_user = {
            'user_id': user.user_id,
            'email': user.email,
            'mobile': user.mobile,
            'junior_name': junior_name,
            'junior_address': junior_address,
            'junior_card': junior_card,
        }

        return jsonify(rest_user)


class UseraCoinBlance(Base_user):
    """查询用户的流水"""
    def get(self):
        parse = self.base_get_parse.parse_args()
        userbalance_model = BalanceHistory.history_model(parse.user_id)

        userbalance = userbalance_model.query.order_by(db.desc(userbalance_model.id)).filter_by(
            user_id = parse.user_id, asset = parse.coin).all()

        if userbalance:
            file_name = './tmp_csv/{}_{}_data.csv'.format(parse.user_id, parse.coin)
            with open(file_name, 'w') as f:
                f_csv = csv.DictWriter(f,  ['time','user_id','asset','business','change','balance'])
                for i in userbalance:
                    f_csv.writerow({
                        'time': str(i.time),
                        'user_id': str(i.user_id),
                        'asset': str(i.asset),
                        'business': str(i.business),
                        'change': str(i.change),
                        'balance': str(i.balance),
                    })
            f.close()
            return marshal(userbalance, self.user_order)
        else:
            return "此用户该币种没有流水"

class UseraLastBlance(Base_user):
    """查询用户已有资产"""
    def get(self):
        user_balance = dict()
        parse = self.base_get_parse.parse_args()
        Userbalance_model = BalanceHistory.history_model(parse.user_id)
        for coin_i in COIN:
            userbalance = Userbalance_model.query.filter_by(
                user_id = parse.user_id, asset = coin_i).order_by(db.desc('id')).limit(10).all()
            if userbalance:
                user_balance[coin_i] = str(userbalance[0].balance)
            else:
                user_balance[coin_i] = '0'
        return jsonify(user_balance)



api.add_resource(SelcetUser, '/userid')
api.add_resource(UseraCoinBlance, '/userbalance')
api.add_resource(UseraLastBlance, '/userlastbalance')

if __name__ == '__main__':
    app.run()
